__author__ = 'guo'

from extends.BaseHandle import BaseHandle
from bson.objectid import ObjectId
import time
import tornado.escape
import tornado.web
import uuid


# 主页
class Index(BaseHandle):
    def get(self):
        cid = self.get_argument("cid", None)

        # self.db.catelog.insert(
        #     [
        #         {'name': '机会', 'parent': 0, 'create': ''},
        #         {'name': '观点', 'parent': 0, 'create': ''},
        #         {'name': '技术', 'parent': 0, 'create': ''},
        #         {'name': '人物', 'parent': 0, 'create': ''},
        #     ]
        # )

        comment_id = self.get_argument("ID", None)
        post_id = self.get_argument("post_id", None)
        acv_ajax = self.get_argument("acv_ajax", None)
        option = self.get_argument("option", None)

        # 点亮操作  没有完成
        if acv_ajax == "true" and option == '1' and comment_id is not None and post_id is not None:
            self.db.article.update({"comment.id": comment_id}, {"$set": {'comment.0.ilike': 1}})
            return self.write("127256|Thank you|1")

        # 每个栏目下面新增一P文章
        # for x in catelist:
        #     self.db.article.insert(
        #         [
        #             {"title": "["+x["name"]+"]金山公司招聘", "content": "要求如下", "author_id": "", "author": "", "looks": '', "create": time.time(), "cid": x['_id']},
        #         ]
        #     )
        # 更新文章
        # self.db.article.update({"title": "[人物]金山公司招聘"}, {"$set": {"cid": cid}})

        artlist = self.db.article.find({})

        if cid is not None:
            catelogInfo = self.db.catelog.find_one({"_id": ObjectId(cid)})
            artlist = self.db.article.find({"cid": cid})
            return self.render("catelog_article.html", xsrf=self.getCookie('_xsrf'), article=artlist, catelog=catelogInfo)

        if artlist is not None:
            articleDict = self.Conver(artlist)

        print(artlist.count())

        for item in articleDict:
            print(item['img'])


        return self.render("index.html", article=articleDict)

    def post(self, *args, **kwargs):
        self.write("this is post")


# 详细页面
# @tornado.web.authenticated
class Detail(BaseHandle):

    # @property
    def IsFavorties(self, id):
        if not self.current_user:
            return False
        favorites = self.db.favorites.find_one({'pid': id, 'uid': self.get_current_user()['_id']})

        if favorites is None:
            return False
        else:
            return True

    def get(self):
        id = self.get_argument("id", None)
        if id is None:
            self.redirect("/404")
        # 浏览次数加1

        article = self.db.article.find_one({"_id": ObjectId(id)})

        self.db.article.update({"_id": ObjectId(id)}, {'$set': {'looks': article['looks']+1}})

        # 如果文章的没有cname 就加上
        catelog = self.db.catelog.find_one({"_id": ObjectId(article['cid'])})
        self.db.article.update({"_id": ObjectId(id)}, {'$set': {'cname': catelog['name']}}, upsert=True)

        return self.render("detail.html", isFavortie=self.IsFavorties(id), article=article, commentCount=len(article['comment']))

    def post(self):
        title = self.get_argument("title", None)
        content = self.get_argument("content", None)
        blog = dict()
        if title and content:
            blog["title"] = title
            blog["content"] = content
            blog["date"] = int(time.time())
            coll = self.application.db.blog
            coll.insert(blog)
            self.redirect("/blog")
        self.redirect("/")


class Comment(BaseHandle):
    def get(self, *args, **kwargs):
        return self.render("")

    @tornado.web.authenticated
    def post(self, *args, **kwargs):
        author = ""
        email = ""
        comment_post_ID = self.get_argument("comment_post_ID")
        if not self.current_user:
            author = self.get_argument("author", '')
            email = self.get_argument("email", '')
        else:
            author = self.get_current_user()['uname']
            email = self.get_current_user()['email']

        comment_time = str(int(time.time()))
        comment = self.get_argument("comment", '')

        comment_mail_notify = self.get_argument("comment_mail_notify", '')
        comment_parent = self.get_argument("comment_parent", '')
        commentUid = str(uuid.uuid1()).replace("-", '')
        # childrenUid = str(uuid.uuid4()).replace("-", '')

        if comment_parent == '0':
            commentJson = {'text': comment, 'time': comment_time, 'author': author, 'email': '', 'id': commentUid, 'parent_id': '', 'ilike': 0, 'avatar': ''}
        else:
            commentJson = {'text': comment, 'time': comment_time, 'author': author, 'email': '', 'id': commentUid, 'parent_id': comment_parent, 'ilike': 0, 'avatar': ''}
        self.db.article.update(
            {'_id': ObjectId(comment_post_ID)},
            {
                '$push': {'comment': commentJson}
            }
        )

        returnStr = "<li class='comment even thread-even depth-1' id='li-comment-"+commentUid+"'><div id='comment-127082'>" \
                    "<div class='photo'><img src='http://image.3001.net/images/index/wp-user-avatar-50x50.png'></div>" \
                    "<div class='tit'>" \
                    "<span class='name'>"+author+"</span> " \
                    "<span class='says'>says:</span>" \
                    "<span class='time'>您的评论正在等待审核。</span>" \
                    "<span class='time'><a href='http://www.freebuf.com/jobs/72884.html/comment-page-1#comment-"+commentUid+"'>"+comment_time+"</a></span>" \
                    "</div>" \
                    "<div class='txt'><p>"+comment+"</p>" \
                    "<div class='vote' id='vote-"+commentUid+"'>" \
                    "<span id='acv_stat_"+commentUid+"'></span>" \
                    "<a class='ilike_icon'  id='vote4-"+commentUid+"'href='javascript:acv_vote("+commentUid+",1);'>亮了</a>(<span id='cos_support-"+commentUid+"'>0</span>)" \
                    "</div>" \
                    "</div>" \
                    "</div>"
        return self.write(returnStr)


class Search(BaseHandle):
    def data_received(self, chunk):
        pass

    def get(self, *args, **kwargs):
        keywords = self.get_argument("keywords", 'jack')
        print(keywords)
        result = self.db.article.find({"author": '/' + keywords + '/'}).count()
        print(result)
        kwargs['result'] = result
        kwargs['name'] = "你好呀你好呀"
        return self.render("search/search.html", **kwargs)

    def post(self, *args, **kwargs):
        pass

